"""
操作系统管理主界面 - 统一样式版本
"""

import logging
from typing import Dict, Any, List
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QTableWidget, QTableWidgetItem, QHeaderView,
    QPushButton, QLabel, QLineEdit, QComboBox,
    QGroupBox, QSplitter, QTextEdit, QMessageBox,
    QProgressBar, QFrame, QTabWidget, QMenu, QAction
)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtWidgets import QDialog

from src.app.modules.os.service import OsService
from src.app.modules.os.utils import OsUtils
from src.app.modules.asset.service import AssetService
from .os_dialog import OsDialog

logger = logging.getLogger(__name__)

class OsWidget(QWidget):
    """操作系统管理主界面"""
    
    # 信号定义
    status_message = pyqtSignal(str)
    os_changed = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.service = OsService()
        self.utils = OsUtils()
        self.asset_service = AssetService()
        self.current_data = []
        self.current_filters = {}
        
        # 初始化UI
        self.init_ui()
        
        # 设置定时刷新
        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh_statistics)
        self.refresh_timer.start(30000)  # 30秒刷新一次
        
        # 延迟加载数据
        QTimer.singleShot(100, self.load_data)
    
    def init_ui(self):
        """初始化UI界面"""
        layout = QVBoxLayout(self)
        
        # 创建分割器
        splitter = QSplitter(Qt.Vertical)
        layout.addWidget(splitter)
        
        # 上部分：统计信息和筛选
        top_widget = self.create_top_widget()
        splitter.addWidget(top_widget)
        
        # 下部分：列表和详情
        bottom_widget = self.create_bottom_widget()
        splitter.addWidget(bottom_widget)
        
        # 设置分割器比例
        splitter.setSizes([200, 500])
    
    def create_top_widget(self):
        """创建上部分组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 统计信息组
        stats_group = self.create_statistics_group()
        layout.addWidget(stats_group)
        
        # 筛选条件组
        filter_group = self.create_filter_group()
        layout.addWidget(filter_group)
        
        return widget
    
    def create_statistics_group(self):
        """创建统计信息组"""
        group = QGroupBox("模块统计")
        layout = QGridLayout(group)
        
        # 总数统计
        layout.addWidget(QLabel("总数:"), 0, 0)
        self.total_count_label = QLabel("0")
        self.total_count_label.setStyleSheet(
            "font-size: 24px; font-weight: bold; color: #2196F3;"
        )
        layout.addWidget(self.total_count_label, 0, 1)
        
        # 按类型分布
        layout.addWidget(QLabel("Linux系统:"), 0, 2)
        self.linux_count_label = QLabel("0")
        self.linux_count_label.setStyleSheet(
            "font-size: 24px; font-weight: bold; color: #4CAF50;"
        )
        layout.addWidget(self.linux_count_label, 0, 3)
        
        # Windows系统
        layout.addWidget(QLabel("Windows系统:"), 1, 0)
        self.windows_count_label = QLabel("0")
        self.windows_count_label.setStyleSheet(
            "font-size: 24px; font-weight: bold; color: #FF9800;"
        )
        layout.addWidget(self.windows_count_label, 1, 1)
        
        # 其他系统
        layout.addWidget(QLabel("其他系统:"), 1, 2)
        self.other_count_label = QLabel("0")
        self.other_count_label.setStyleSheet(
            "font-size: 24px; font-weight: bold; color: #9C27B0;"
        )
        layout.addWidget(self.other_count_label, 1, 3)
        
        return group
    
    def create_filter_group(self):
        """创建筛选条件组"""
        group = QGroupBox("筛选条件")
        layout = QGridLayout(group)
        
        # 设备资产筛选
        layout.addWidget(QLabel("设备资产:"), 0, 0)
        self.asset_combo = QComboBox()
        self.asset_combo.setMinimumWidth(150)
        layout.addWidget(self.asset_combo, 0, 1)
        
        # 操作系统名称筛选
        layout.addWidget(QLabel("操作系统:"), 0, 2)
        self.os_name_edit = QLineEdit()
        self.os_name_edit.setPlaceholderText("输入操作系统名称")
        layout.addWidget(self.os_name_edit, 0, 3)
        
        # 版本号筛选
        layout.addWidget(QLabel("版本号:"), 1, 0)
        self.version_edit = QLineEdit()
        self.version_edit.setPlaceholderText("输入版本号")
        layout.addWidget(self.version_edit, 1, 1)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        self.search_button = QPushButton("🔍 搜索")
        self.search_button.clicked.connect(self.search_data)
        button_layout.addWidget(self.search_button)
        
        self.reset_button = QPushButton("🔄 重置")
        self.reset_button.clicked.connect(self.reset_filters)
        button_layout.addWidget(self.reset_button)
        
        self.refresh_button = QPushButton("🔄 刷新")
        self.refresh_button.clicked.connect(self.load_data)
        button_layout.addWidget(self.refresh_button)
        
        layout.addLayout(button_layout, 1, 2, 1, 2)
        
        return group
    
    def create_bottom_widget(self):
        """创建下部分组件"""
        splitter = QSplitter(Qt.Horizontal)
        
        # 左侧：数据列表
        left_widget = self.create_list_widget()
        splitter.addWidget(left_widget)
        
        # 右侧：详情面板
        right_widget = self.create_detail_widget()
        splitter.addWidget(right_widget)
        
        # 设置分割器比例
        splitter.setSizes([400, 200])
        
        return splitter
    
    def create_list_widget(self):
        """创建数据列表组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 标题和操作按钮
        title_layout = QHBoxLayout()
        
        title_label = QLabel("操作系统列表")
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(12)
        title_label.setFont(title_font)
        title_layout.addWidget(title_label)
        
        title_layout.addStretch()
        
        self.add_button = QPushButton("➕ 新增")
        self.add_button.clicked.connect(self.add_os)
        title_layout.addWidget(self.add_button)
        
        self.edit_button = QPushButton("✏️ 编辑")
        self.edit_button.clicked.connect(self.edit_os)
        self.edit_button.setEnabled(False)
        title_layout.addWidget(self.edit_button)
        
        self.delete_button = QPushButton("🗑️ 删除")
        self.delete_button.clicked.connect(self.delete_os)
        self.delete_button.setEnabled(False)
        title_layout.addWidget(self.delete_button)
        
        layout.addLayout(title_layout)
        
        # 数据表格
        self.data_table = QTableWidget()
        self.data_table.setColumnCount(7)
        self.data_table.setHorizontalHeaderLabels([
            "操作系统ID", "设备资产", "操作系统名称", "版本号", 
            "安装目录", "安装日期", "关联数量"
        ])
        
        # 设置表格属性
        header = self.data_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)  # ID列
        header.setSectionResizeMode(1, QHeaderView.Stretch)  # 设备资产列
        header.setSectionResizeMode(2, QHeaderView.Stretch)  # 操作系统名称列
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)  # 版本号列
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)  # 安装目录列
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)  # 安装日期列
        header.setSectionResizeMode(6, QHeaderView.ResizeToContents)  # 关联数量列
        
        self.data_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.data_table.setSelectionMode(QTableWidget.SingleSelection)
        self.data_table.setAlternatingRowColors(True)
        self.data_table.itemSelectionChanged.connect(self.on_selection_changed)
        self.data_table.itemDoubleClicked.connect(self.edit_os)
        
        layout.addWidget(self.data_table)
        
        return widget
    
    def create_detail_widget(self):
        """创建详情面板组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 标题
        title_label = QLabel("详细信息")
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(12)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 标签页
        self.detail_tabs = QTabWidget()
        
        # 基本信息标签页
        basic_widget = QWidget()
        basic_layout = QVBoxLayout(basic_widget)
        
        self.basic_info_text = QTextEdit()
        self.basic_info_text.setReadOnly(True)
        self.basic_info_text.setMaximumHeight(200)
        basic_layout.addWidget(self.basic_info_text)
        
        self.detail_tabs.addTab(basic_widget, "基本信息")
        
        # 业务系统标签页
        business_widget = QWidget()
        business_layout = QVBoxLayout(business_widget)
        
        self.business_table = QTableWidget()
        self.business_table.setColumnCount(5)
        self.business_table.setHorizontalHeaderLabels([
            "系统ID", "系统类型", "系统名称", "负责人", "部门"
        ])
        
        business_header = self.business_table.horizontalHeader()
        business_header.setSectionResizeMode(QHeaderView.Stretch)
        self.business_table.setAlternatingRowColors(True)
        self.business_table.setMaximumHeight(150)
        
        business_layout.addWidget(self.business_table)
        self.detail_tabs.addTab(business_widget, "业务系统")
        
        # 中间件标签页
        middleware_widget = QWidget()
        middleware_layout = QVBoxLayout(middleware_widget)
        
        self.middleware_table = QTableWidget()
        self.middleware_table.setColumnCount(5)
        self.middleware_table.setHorizontalHeaderLabels([
            "中间件ID", "类型", "名称", "版本", "端口"
        ])
        
        middleware_header = self.middleware_table.horizontalHeader()
        middleware_header.setSectionResizeMode(QHeaderView.Stretch)
        self.middleware_table.setAlternatingRowColors(True)
        self.middleware_table.setMaximumHeight(150)
        
        middleware_layout.addWidget(self.middleware_table)
        self.detail_tabs.addTab(middleware_widget, "中间件")
        
        # IP地址标签页
        ip_widget = QWidget()
        ip_layout = QVBoxLayout(ip_widget)
        
        self.ip_table = QTableWidget()
        self.ip_table.setColumnCount(6)
        self.ip_table.setHorizontalHeaderLabels([
            "IP地址", "子网掩码", "VLAN", "用途", "状态", "分配时效"
        ])
        
        ip_header = self.ip_table.horizontalHeader()
        ip_header.setSectionResizeMode(QHeaderView.Stretch)
        self.ip_table.setAlternatingRowColors(True)
        self.ip_table.setMaximumHeight(150)
        
        ip_layout.addWidget(self.ip_table)
        self.detail_tabs.addTab(ip_widget, "IP地址")
        
        layout.addWidget(self.detail_tabs)
        
        return widget
    
    def load_data(self):
        """加载数据"""
        try:
            # 加载设备资产列表
            self.load_assets()
            
            # 加载操作系统列表
            self.load_os_list()
            
            # 加载统计信息
            self.load_statistics()
            
            self.status_message.emit("数据加载完成")
            
        except Exception as e:
            logger.error(f"加载数据失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"加载数据失败: {str(e)}")
    
    def load_assets(self):
        """加载设备资产列表"""
        try:
            assets = self.asset_service.get_all_assets()
            
            self.asset_combo.clear()
            self.asset_combo.addItem("全部", None)
            
            for asset in assets:
                display_text = f"{asset['asset_name']} ({asset['asset_type']})"
                self.asset_combo.addItem(display_text, asset['asset_id'])
                
        except Exception as e:
            logger.error(f"加载设备资产列表失败: {str(e)}")
    
    def load_os_list(self):
        """加载操作系统列表"""
        try:
            # 获取筛选条件
            filters = self.get_current_filters()
            
            # 获取数据
            os_list = self.service.get_os_list(filters)
            self.current_data = os_list
            
            # 更新表格
            self.update_table()
            
        except Exception as e:
            logger.error(f"加载操作系统列表失败: {str(e)}")
    
    def load_statistics(self):
        """加载统计信息"""
        try:
            stats = self.service.get_os_statistics()
            
            self.total_count_label.setText(str(stats['total_count']))
            
            # 按操作系统类型统计
            linux_count = 0
            windows_count = 0
            other_count = 0
            
            for os_dist in stats['os_distribution']:
                os_name = os_dist['name'].lower()
                if 'linux' in os_name or 'centos' in os_name or 'ubuntu' in os_name:
                    linux_count += os_dist['count']
                elif 'windows' in os_name:
                    windows_count += os_dist['count']
                else:
                    other_count += os_dist['count']
            
            self.linux_count_label.setText(str(linux_count))
            self.windows_count_label.setText(str(windows_count))
            self.other_count_label.setText(str(other_count))
            
        except Exception as e:
            logger.error(f"加载统计信息失败: {str(e)}")
    
    def update_table(self):
        """更新表格数据"""
        self.data_table.setRowCount(len(self.current_data))
        
        for row, os_data in enumerate(self.current_data):
            # 操作系统ID
            self.data_table.setItem(row, 0, QTableWidgetItem(os_data['os_id']))
            
            # 设备资产
            asset_text = f"{os_data['asset_name']} ({os_data['asset_type']})"
            self.data_table.setItem(row, 1, QTableWidgetItem(asset_text))
            
            # 操作系统名称
            self.data_table.setItem(row, 2, QTableWidgetItem(os_data['os_name']))
            
            # 版本号
            self.data_table.setItem(row, 3, QTableWidgetItem(os_data['version']))
            
            # 安装目录
            install_dir = os_data['install_dir'] or ""
            self.data_table.setItem(row, 4, QTableWidgetItem(install_dir))
            
            # 安装日期
            install_date = os_data['install_date'] or ""
            self.data_table.setItem(row, 5, QTableWidgetItem(install_date))
            
            # 关联数量
            total_relations = (
                os_data['business_systems_count'] + 
                os_data['middlewares_count'] + 
                os_data['ip_count']
            )
            self.data_table.setItem(row, 6, QTableWidgetItem(str(total_relations)))
    
    def get_current_filters(self):
        """获取当前筛选条件"""
        filters = {}
        
        # 设备资产筛选
        asset_id = self.asset_combo.currentData()
        if asset_id:
            filters['asset_id'] = asset_id
        
        # 操作系统名称筛选
        os_name = self.os_name_edit.text().strip()
        if os_name:
            filters['os_name'] = os_name
        
        # 版本号筛选
        version = self.version_edit.text().strip()
        if version:
            filters['version'] = version
        
        return filters
    
    def search_data(self):
        """搜索数据"""
        try:
            self.load_os_list()
            self.status_message.emit("搜索完成")
            
        except Exception as e:
            logger.error(f"搜索失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"搜索失败: {str(e)}")
    
    def reset_filters(self):
        """重置筛选条件"""
        self.asset_combo.setCurrentIndex(0)
        self.os_name_edit.clear()
        self.version_edit.clear()
        
        self.load_os_list()
        self.status_message.emit("筛选条件已重置")
    
    def refresh_statistics(self):
        """刷新统计信息"""
        try:
            self.load_statistics()
            
        except Exception as e:
            logger.error(f"刷新统计信息失败: {str(e)}")
    
    def on_selection_changed(self):
        """选择变化事件"""
        selected_rows = self.data_table.selectedItems()
        has_selection = len(selected_rows) > 0
        
        self.edit_button.setEnabled(has_selection)
        self.delete_button.setEnabled(has_selection)
        
        if has_selection:
            row = self.data_table.currentRow()
            os_data = self.current_data[row]
            self.load_os_details(os_data['os_id'])
        else:
            self.clear_details()
    
    def load_os_details(self, os_id):
        """加载操作系统详细信息"""
        try:
            details = self.service.get_os_details(os_id)
            
            if details:
                # 更新基本信息
                self.update_basic_info(details)
                
                # 更新业务系统
                self.update_business_systems(details.get('business_systems', []))
                
                # 更新中间件
                self.update_middlewares(details.get('middlewares', []))
                
                # 更新IP地址
                self.update_ips(details.get('ips', []))
                
        except Exception as e:
            logger.error(f"加载操作系统详细信息失败: {str(e)}")
    
    def update_basic_info(self, details):
        """更新基本信息"""
        info_text = f"""
<b>操作系统ID:</b> {details['os_id']}
<b>设备资产:</b> {details['asset_name']} ({details['asset_type']})
<b>操作系统名称:</b> {details['os_name']}
<b>版本号:</b> {details['version']}
<b>安装目录:</b> {details['install_dir'] or '未设置'}
<b>安装日期:</b> {details['install_date'] or '未设置'}
<b>创建时间:</b> {details['create_time']}
<b>更新时间:</b> {details['update_time']}
<b>业务系统数量:</b> {details['business_systems_count']}
<b>中间件数量:</b> {details['middlewares_count']}
<b>IP地址数量:</b> {details['ip_count']} (规格要求：1对1绑定)
        """.strip()
        
        self.basic_info_text.setHtml(info_text)
    
    def update_business_systems(self, business_systems):
        """更新业务系统列表"""
        self.business_table.setRowCount(len(business_systems))
        
        for row, bs in enumerate(business_systems):
            self.business_table.setItem(row, 0, QTableWidgetItem(bs['system_id']))
            self.business_table.setItem(row, 1, QTableWidgetItem(bs['system_type']))
            self.business_table.setItem(row, 2, QTableWidgetItem(bs['system_name']))
            self.business_table.setItem(row, 3, QTableWidgetItem(bs['负责人'] or ""))
            self.business_table.setItem(row, 4, QTableWidgetItem(bs['department'] or ""))
    
    def update_middlewares(self, middlewares):
        """更新中间件列表"""
        self.middleware_table.setRowCount(len(middlewares))
        
        for row, mw in enumerate(middlewares):
            self.middleware_table.setItem(row, 0, QTableWidgetItem(mw['mw_id']))
            self.middleware_table.setItem(row, 1, QTableWidgetItem(mw['mw_type']))
            self.middleware_table.setItem(row, 2, QTableWidgetItem(mw['name']))
            self.middleware_table.setItem(row, 3, QTableWidgetItem(mw['version'] or ""))
            self.middleware_table.setItem(row, 4, QTableWidgetItem(str(mw['port']) if mw['port'] else ""))
    
    def update_ips(self, ips):
        """更新IP地址列表"""
        self.ip_table.setRowCount(len(ips))
        
        for row, ip in enumerate(ips):
            self.ip_table.setItem(row, 0, QTableWidgetItem(ip['ip']))
            self.ip_table.setItem(row, 1, QTableWidgetItem(ip['subnet_mask']))
            self.ip_table.setItem(row, 2, QTableWidgetItem(ip['vlan']))
            self.ip_table.setItem(row, 3, QTableWidgetItem(ip['purpose']))
            self.ip_table.setItem(row, 4, QTableWidgetItem(ip['status']))
            self.ip_table.setItem(row, 5, QTableWidgetItem(ip['allocation_duration']))
    
    def clear_details(self):
        """清除详细信息"""
        self.basic_info_text.clear()
        self.business_table.setRowCount(0)
        self.middleware_table.setRowCount(0)
        self.ip_table.setRowCount(0)
    
    def add_os(self):
        """新增操作系统"""
        try:
            dialog = OsDialog(self)
            if dialog.exec_() == QDialog.Accepted:
                self.load_data()
                self.os_changed.emit()
                self.status_message.emit("操作系统添加成功")
                
        except Exception as e:
            logger.error(f"新增操作系统失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"新增操作系统失败: {str(e)}")
    
    def edit_os(self):
        """编辑操作系统"""
        try:
            selected_rows = self.data_table.selectedItems()
            if not selected_rows:
                return
            
            row = self.data_table.currentRow()
            os_data = self.current_data[row]
            
            dialog = OsDialog(self, os_data)
            if dialog.exec_() == QDialog.Accepted:
                self.load_data()
                self.os_changed.emit()
                self.status_message.emit("操作系统更新成功")
                
        except Exception as e:
            logger.error(f"编辑操作系统失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"编辑操作系统失败: {str(e)}")
    
    def delete_os(self):
        """删除操作系统"""
        try:
            selected_rows = self.data_table.selectedItems()
            if not selected_rows:
                return
            
            row = self.data_table.currentRow()
            os_data = self.current_data[row]
            
            # 确认删除
            reply = QMessageBox.question(
                self, "确认删除",
                f"确定要删除操作系统 '{os_data['os_name']} {os_data['version']}' 吗？\n\n"
                "注意：如果该操作系统下有关联的业务系统、中间件或IP地址，将无法删除。",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                result = self.service.delete_os(os_data['os_id'])
                
                if result['success']:
                    self.load_data()
                    self.os_changed.emit()
                    self.status_message.emit("操作系统删除成功")
                else:
                    QMessageBox.warning(self, "警告", result['message'])
                    
        except Exception as e:
            logger.error(f"删除操作系统失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"删除操作系统失败: {str(e)}")